package Thread2;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

// 实现一个固定线程个数的线程池
class MyThreadPool2{
    private BlockingQueue<Runnable> queue = null;

    public MyThreadPool2(int n){
        // 初始化线程池,创建固定个数的线程池
        // 使用ArrayBlockingQueue 作为任务队列,容量为1000
        queue = new ArrayBlockingQueue<>(1000);

        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
                while(true){
                    try {
                        Runnable task = queue.take();
                        task.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });

            t.start();
        }
    }

    public void submit(Runnable task) throws InterruptedException {
        queue.put(task);
    }
}
public class Homework7 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool2 threadPool = new MyThreadPool2(10);

        // 向线程池里提交任务
        for (int i = 0; i < 100; i++) {
            int id = i;
            threadPool.submit(() -> {
                System.out.println("Hello " + id +"," + Thread.currentThread().getName());
            });
        }
    }
}
